package com.kaiyidiannao.activity.softVersion;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.*;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.webkit.MimeTypeMap;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.kaiyidiannao.common.util.SharedPreferencesUtil;
import com.kaiyidiannao.data.Constants;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.req.model.GetSoftVersion;
import com.kaiyidiannao.view.ActionBarView;
import com.kaiyidiannao.widget.LoadingDialog;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by wzg on 14-5-9.
 */
public class SoftVersionActivity extends Activity implements Observer {
    private static String TAG = "SoftVersion :";
    public static final String softverionIsDownload = "softverionIsDownload";
    private ActionBarView actionBarView;
    private ImageButton btVersion;
    private DownloadManager downloadManager;
    private SharedPreferences prefs;
    private float version = -1.0f;
    private TextView textView;
    private AlertDialog.Builder alertDialog = null;
    private static final String DL_ID = "downloadId";
    private int status;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d("action", action + "    0000000000");
            //这里可以取得下载的id，这样就可以知道哪个文件下载完成了。适用与多个下载任务的监听
            Log.v("intent", "" + intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));
            queryDownloadStatus();
        }
    };

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                Toast.makeText(SoftVersionActivity.this, id + " Finished", Toast.LENGTH_SHORT).show();
            } else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {//通知栏点击事件
                return;
               // long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
            } else if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                Intent intent1 = new Intent(Intent.ACTION_VIEW);
                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent1.setDataAndType(Uri.parse("file://" + "/download/"),
                        "application/vnd.android.package-archive");
                getApplicationContext().startActivity(intent1);
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.soft_version);
        DataCenter.getInstance().addObserver(this);
        downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        version = getVersion(this);
        textView = (TextView) findViewById(R.id.textView);
        textView.setText("版本号: V" + version + "");
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_REMOVED);
        filter.addAction(Intent.ACTION_MEDIA_EJECT);
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addDataScheme("file");
        registerReceiver(receiver, filter);
        initView();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        unregisterReceiver(mReceiver);
        super.onDestroy();
    }

    public float getVersion(Context context) {
        try {
            PackageInfo manager = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return manager.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            return -1.0f;
        }
    }

    public void initView() {
        actionBarView = (ActionBarView) findViewById(R.id.actionbar);
        actionBarView.title.setText("软件版本");
        btVersion = (ImageButton) findViewById(R.id.btVersion);
        btVersion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("SoftVersion", isFolderExist("/Download/") + "");
                if (isFolderExist("/Download/")) {
//                    File file = Environment.getExternalStoragePublicDirectory("/Download/kaiyi.apk");
//                    Log.d("OnclickListener",file.getPath().toString());
//                    Log.d("SoftVersion", file.exists() + "  File");
//                    if (file.exists()) {
                    boolean isDownload = false;
                    try {
                        isDownload = SharedPreferencesUtil.getBoolean(Constants.shareName, Constants.shareKey_softversion_isdownload);
                    } catch (Exception e) {
                        SharedPreferencesUtil.putBoolean(Constants.shareName, Constants.shareKey_softversion_isdownload, false);
                        e.printStackTrace();
                    }
                    if (isDownload) {
                        Toast.makeText(SoftVersionActivity.this, "正在下载中,请稍后...", Toast.LENGTH_SHORT).show();
                        DownloadManager.Query query = new DownloadManager.Query();
//                        Log.d("SoftVersion", file.exists() + "  FileExist");
                        query.setFilterById(prefs.getLong(DL_ID, 0));
                        Cursor c = downloadManager.query(query);
                        if (c.moveToFirst()) {
                            status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                            switch (status) {
                                case DownloadManager.STATUS_PAUSED:
                                    Log.v("down", "STATUS_PAUSED");
                                case DownloadManager.STATUS_PENDING:
                                    Log.v("down", "STATUS_PENDING");
                                case DownloadManager.STATUS_RUNNING:
                                    //正在下载，不做任何事情
                                    Log.v("down", "STATUS_RUNNING");
                                    Toast.makeText(SoftVersionActivity.this, "正在下载中,请稍后...", Toast.LENGTH_SHORT).show();
                                    return;
                                case DownloadManager.STATUS_SUCCESSFUL:
                                    //完成
                                    Log.v("down", "下载完成");
                                    SharedPreferencesUtil.putBoolean(Constants.shareName, Constants.shareKey_softversion_isdownload, false);
                                    Intent intent = new Intent(Intent.ACTION_VIEW);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    intent.setDataAndType(Uri.parse("file://" + "/download/"),
                                            "application/vnd.android.package-archive");
                                    getApplicationContext().startActivity(intent);
                                    return;
                                case DownloadManager.STATUS_FAILED:
                                    //清除已下载的内容，重新下载
                                    Log.v("down", "STATUS_FAILED");
                                    downloadManager.remove(prefs.getLong(DL_ID, 0));
                                    prefs.edit().clear().commit();
                                    break;
                            }
                        }
                    } else {
//                        Log.d("SoftVersion", file.exists() + "  FileNoExist");
                        showProgressDialog();
                        prefs.edit().clear().commit();
                        new GetSoftVersion().execute();
                    }
                }
            }
        });
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        intentFilter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED);
        registerReceiver(mReceiver, intentFilter);
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    public String encodeGB(String string) {
        //转换中文编码
        String split[] = string.split("/");
        for (int i = 1; i < split.length; i++) {
            try {
                split[i] = URLEncoder.encode(split[i], "GB2312");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            split[0] = split[0] + "/" + split[i];
        }
        split[0] = split[0].replaceAll("\\+", "%20");//处理空格
        return split[0];
    }

    private boolean isFolderExist(String dir) {
        File folder = Environment.getExternalStoragePublicDirectory(dir);
        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
    }

    @Override
    public void update(Observable observable, Object data) {
        closeProgressDialog();
        DataCenter.flag flag = (DataCenter.flag) data;
        if (flag == DataCenter.flag.GET_SOFTVERSION_SUCCESS) {
            if (null == DataCenter.version || "".equals(DataCenter.version)) {
                Toast.makeText(SoftVersionActivity.this, DataCenter.resultes, Toast.LENGTH_SHORT).show();
                return;
            }
            if (version < Float.parseFloat(DataCenter.version)) {
                SharedPreferencesUtil.putBoolean(Constants.shareName, Constants.shareKey_softversion_isdownload, false);
                alertDialog =   new AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("有新版" + DataCenter.version + ",是否更新?")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                alertDialog = null;
                                updateSoft();
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                alertDialog = null;
                            }
                        })
                        .setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                alertDialog = null;
                            }
                        })
                       ;
//
            } else {
                Toast.makeText(this, "已是最新版本,无需更新", Toast.LENGTH_SHORT).show();
                return;
            }
        }
    }

    private void updateSoft() {
        if (!prefs.contains(DL_ID)) {
            String url = "http://www.3tixa.com:8086/kaiyi/api/app/download.php";
            //开始下载
            SharedPreferencesUtil.putBoolean(Constants.shareName, Constants.shareKey_softversion_isdownload, true);
            Log.d("prefs", url);
            Uri resource = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(resource);
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
            request.setAllowedOverRoaming(false);
            //设置文件类型
            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
            String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
            request.setMimeType(mimeString);
            //在通知栏中显示
            request.setNotificationVisibility(View.VISIBLE);
            request.setVisibleInDownloadsUi(true);
            //sdcard的目录下的download文件夹
            String dir = "/Download/";
            isFolderExist(dir);
            request.setDestinationInExternalPublicDir(dir, "kaiyi_v" + DataCenter.version + ".apk");
            request.setTitle("凯翼电脑");
            long id = downloadManager.enqueue(request);
            //保存id
//                    Toast.makeText(SoftVersionActivity.this, "后台开始下载,请不要要退出程序", Toast.LENGTH_SHORT).show();
            prefs.edit().putLong(DL_ID, id).commit();
        } else {
            //下载已经开始，检查状态
            queryDownloadStatus();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        //onWindowFocusChanged指的是这个Activity得到或者失去焦点的时候 就会call
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){
           if (alertDialog != null) {
               alertDialog.show();
           }
        }
    }

    private void queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(prefs.getLong(DL_ID, 0));
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
                    Log.v("down", "STATUS_PAUSED");
                case DownloadManager.STATUS_PENDING:
                    Log.v("down", "STATUS_PENDING");
                case DownloadManager.STATUS_RUNNING:
                    //正在下载，不做任何事情
                    Log.v("down", "STATUS_RUNNING");
                    Toast.makeText(SoftVersionActivity.this, "正在下载中,请稍后...", Toast.LENGTH_SHORT).show();
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    //完成
                    Log.v("down", "下载完成");
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(Uri.parse("file://" + "/download/"),
                            "application/vnd.android.package-archive");
                    getApplicationContext().startActivity(intent);
                    break;
                case DownloadManager.STATUS_FAILED:
                    //清除已下载的内容，重新下载
                    Log.v("down", "STATUS_FAILED");
                    downloadManager.remove(prefs.getLong(DL_ID, 0));
                    prefs.edit().clear().commit();
                    break;
            }
        }
    }

    protected LoadingDialog dialog;

    public void showProgressDialog(String str) {
        if (dialog == null) {
            dialog = new LoadingDialog(this);
            dialog.setCanceledOnTouchOutside(false);
        }
        dialog.setText(str);
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    public void showProgressDialog() {
        this.showProgressDialog("正在加载...");
    }

    public void closeProgressDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }
}

